package com.zhaoyu.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.zhaoyu.admin.feign.article.ArticleFeign;
import com.zhaoyu.admin.feign.wemedia.WemediaFeign;
import com.zhaoyu.admin.mapper.AdChannelMapper;
import com.zhaoyu.admin.mapper.AdSensitiveMapper;
import com.zhaoyu.admin.service.WemediaNewsAutoScanService;
import com.zhaoyu.common.aliyun.GreeTextScan;
import com.zhaoyu.common.aliyun.GreenImageScan;
import com.zhaoyu.common.constants.WemediaConstants;
import com.zhaoyu.common.fastdfs.FastDFSClient;
import com.zhaoyu.model.admin.dtos.NewsAuthDto;
import com.zhaoyu.model.admin.pojos.AdChannel;
import com.zhaoyu.model.article.pojos.ApArticle;
import com.zhaoyu.model.article.pojos.ApArticleConfig;
import com.zhaoyu.model.article.pojos.ApArticleContent;
import com.zhaoyu.model.article.pojos.ApAuthor;
import com.zhaoyu.model.common.dtos.ResponseResult;
import com.zhaoyu.model.common.enums.AppHttpCodeEnum;
import com.zhaoyu.model.media.pojos.WmNews;
import com.zhaoyu.model.media.pojos.WmUser;
import com.zhaoyu.model.media.vo.WmNewsCheckVO;
import com.zhaoyu.utils.common.SensitiveWordUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Log4j2
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private AdChannelMapper adChannelMapper;

    @Autowired
    private GreeTextScan greeTextScan;

    @Value("${fileServerUrl}")
    private String fileServerUrl; // 图片服务器地址

    @Autowired
    private FastDFSClient fastDFSClient;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private AdSensitiveMapper adSensitiveMapper;

    @Override
    // @GlobalTransactional // 分布式事务
    public void autoScanByMediaNewsId(Integer id) {
        if (id == null) {
            log.error("id is null");
            // log.error("当前的审核id空");
            return;
        }
        // 根据Id查询自媒体图文内容
        WmNews wmNews = wemediaFeign.findWmNewsByIdSTL(id);
        if (wmNews == null) {
            log.error("wmNews is null");
            // log.error("审核的自媒体文章不存在,自媒体的id:{}", id);
            return;
        }
        // 文章状态为4,即人工审核通过
        if (wmNews.getStatus() == 4) {
            // 保存app文章相关的数据
            saveArticle(wmNews);
            return;
        }
        // 文章状态为8,发布时间<=当前时间,直接保存数据
        if (wmNews.getStatus() == 8 && wmNews.getPublishTime().getTime() <= new Date().getTime()) {
            // 保存app文章相关的数据
            saveArticle(wmNews);
            return;
        }
        // 文章未审核
        if (wmNews.getStatus() == 1) {
            // 抽取文章内容中的纯文本和图片
            Map<String, Object> contentAndImagesResult = handleTextAndImages(wmNews);
            // 文本审核
            boolean textScanBoolean = handleTextScan(String.valueOf(contentAndImagesResult.get("content")),wmNews);
            if (!textScanBoolean) {
                return;
            }
            // 图片审核
            boolean imagesScanBoolean = handleImagesScan((List<String>) contentAndImagesResult.get("images"),wmNews);
            if (!imagesScanBoolean) {
                return;
            }
            // 自管理的敏感词审核
            boolean sensitiveScanBoolean = handleSensitive(String.valueOf(contentAndImagesResult.get("content")),wmNews);
            if (!sensitiveScanBoolean) {
                return;
            }
            // 发布时间大于当前时间
            if (wmNews.getPublishTime().getTime() > new Date().getTime()) {
                // 修改文章状态为8
                updateWmNews(wmNews,(short)8,"审核通过,待发布");
                return;
            }
            // 调三方接口校验内容
            // 审核成功后,保存数据到Article
            // 审核通过,修改自媒体文章状态为9,保存app端相关文章信息
            saveArticle(wmNews);
        }
    }

    /**
     * 自管理的敏感词审核
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        List<String> sensitiveAll = adSensitiveMapper.findAllSensitive();
        // 初始化敏感词
        SensitiveWordUtil.initMap(sensitiveAll);
        // 文章内容自管理敏感词过滤
        Map<String, Integer> resultMap = SensitiveWordUtil.matchWords(content);
        if(resultMap.size() > 0){
            log.error("敏感词过滤没有通过,包含了敏感词:{}", resultMap);
            // 找到了敏感词,审核不通过
            updateWmNews(wmNews,(short)2,"文章中包含了敏感词");
            flag = false;
        }
        return flag;
    }

    /**
     * 图片审核
     */
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        if (images == null) {
            return true;
        }
        boolean flag = true;
        List<byte[]> imageList = new ArrayList<>();
        try {
            for (String image : images) {
                String replace = image.replace(fileServerUrl, "");
                int index = replace.indexOf("/");
                String groupName = replace.substring(0, index);
                String imagePath = replace.substring(index + 1);
                byte[] imageByte = fastDFSClient.downloadFile(groupName, imagePath);
                imageList.add(imageByte);
            }
            // 阿里云图片审核
            Map map = greenImageScan.imageScan(imageList);
            // 审核不通过
            if(!map.get("suggestion").equals("pass")){
                // 审核失败
                if (map.get("suggestion").equals("block")) {
                    // 修改自媒体文章的状态,并告知审核失败原因
                    updateWmNews(wmNews,(short)2,"文章中图片有违规");
                    flag = false;
                }
                // 人工审核
                if (map.get("suggestion").equals("review")) {
                    // 修改自媒体文章的状态,并告知审核失败原因
                    updateWmNews(wmNews,(short)3,"文章图片有不确定元素");
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 文本审核
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        try {
            Map map = greeTextScan.greeTextScan(content);
            // 审核不通过
            if (!map.get("suggestion").equals("pass")){
                // 审核失败
                if (map.get("suggestion").equals("block")){
                    // 修改自媒体文章的状态,并告知审核失败原因
                    updateWmNews(wmNews,(short) 2,"文章内容中有敏感词汇");
                    flag = false;
                }
                // 人工审核
                if (map.get("suggestion").equals("review")) {
                    // 修改自媒体文章的状态,并告知审核失败原因
                    updateWmNews(wmNews, (short) 3, "文章内容中有不确定词汇");
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 抽取文章内容中的纯文本和图片
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        String content = wmNews.getContent(); // 文章内容
        StringBuffer stringBuffer = new StringBuffer(); // 存储纯文本内容
        List<String> images = new ArrayList<>(); // 存储图片
        // 转Map
        List<Map> contentList = JSONArray.parseArray(content, Map.class);
        for (Map map : contentList) { // 遍历文章内容
            if (map.get("type").equals("text")) { // 文本类型
                stringBuffer.append(map.get("value"));
            }
            if (map.get("type").equals("image")) { // 图片类型
                images.add(map.get("value").toString());
            }
        }
        if (wmNews.getImages() != null && wmNews.getType() != 0) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", stringBuffer.toString());
        resultMap.put("images", images);
        return resultMap;
    }

    /**
     * 保存app文章相关的数据
     */
    private void saveArticle(WmNews wmNews) {
        // 保存app文章 保存完了 必须要把主建id返回来
        ApArticle apArticle = saveApArticle(wmNews);
        // 保存app文章配置
        saveApArticleConfig(apArticle);
        // 保存app文章内容
        saveApArticleContent(apArticle,wmNews);
        // 修改自媒体文章的状态为9
        updateWmNews(wmNews,(short)9,"审核通过");
    }

    /**
     * 修改自媒体文章的状态为9
     */
    private void updateWmNews(WmNews wmNews, short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wemediaFeign.updateWmNews(wmNews);
    }

    /**
     * 保存app文章内容
     */
    private void saveApArticleContent(ApArticle apArticle, WmNews wmNews) {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId()); // 文章id
        apArticleContent.setContent(wmNews.getContent()); // 文章内容
        articleFeign.saveApArticleContent(apArticleContent);
    }

    /**
     * 保存app文章配置
     */
    private void saveApArticleConfig(ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId()); // 文章id
        apArticleConfig.setIsForward(true); // 是否转发
        apArticleConfig.setIsDelete(false); // 是否已删除
        apArticleConfig.setIsDown(true); // 是否下架
        apArticleConfig.setIsComment(true); // 是否可评论
        articleFeign.saveApArticleConfig(apArticleConfig);
    }

    /**
     * 保存app文章
     */
    private ApArticle saveApArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle()); // 标题
        apArticle.setLayout(wmNews.getType()); // 文章布局
        apArticle.setImages(wmNews.getImages()); // 文章封面图片
        apArticle.setCreatedTime(new Date()); // 创建时间
        apArticle.setPublishTime(wmNews.getPublishTime()); // 发布时间
        // 获取作者相关信息
        Integer userId = wmNews.getUserId();
        WmUser wmUser = wemediaFeign.findByIdWmUser(Long.valueOf(userId));
        if (wmUser != null) {
            String name = wmUser.getName();
            ApAuthor apAuthor = articleFeign.findByNameApAuthor(name);
            if (apAuthor != null) {
                apArticle.setAuthorId(apAuthor.getId().longValue()); // 作者id
                apArticle.setAuthorName(apAuthor.getName()); // 作者名称
            }
        }
        // 获取频道相关信息
        Integer channelId = wmNews.getChannelId();
        AdChannel adChannel = adChannelMapper.selectById(channelId);
        if (channelId != null) {
            apArticle.setChannelId(adChannel.getId()); // 频道id
            apArticle.setChannelName(adChannel.getName()); // 频道名称
        }
        return articleFeign.saveApArticle(apArticle);
    }

    @Override
    public ResponseResult findWmNews(NewsAuthDto newsAuthDto) {
        // 分页查询
        ResponseResult responseResult = wemediaFeign.findListWmNews(newsAuthDto);
        // 有图片需要显示,需要FastDFS服务器地址
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        // 检查参数
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 查询数据
        WmNewsCheckVO wmNewsCheckVO = wemediaFeign.findWmNewsCheckVO(id);
        // 结果封装
        ResponseResult responseResult = ResponseResult.okResult(wmNewsCheckVO);
        // 有图片需要显示,需要FastDFS服务器地址
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(Integer type, NewsAuthDto newsAuthDto) {
        // 检查参数
        if (newsAuthDto == null || newsAuthDto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 查询文章
        WmNews wmNews = wemediaFeign.findWmNewsByIdSTL(newsAuthDto.getId());
        if (wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 审核没有通过
        if (type.equals(WemediaConstants.OVERRULE)){
            updateWmNews(wmNews,(short)2,newsAuthDto.getMsg());
        }else if (type.equals(WemediaConstants.PASS)){
            updateWmNews(wmNews,(short)4,"人工审核通过"); // 人工审核通过
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}